//
//  DSHisViewController.m
//  zuixin
//
//  Created by QJY on 14-8-20.
//  Copyright (c) 2014年 dingshenwangluokeji. All rights reserved.
//

#import "DSHisViewController.h"
#import "NetAccess.h"
#import "Header.h"
#import "SecurityUtil.h"
#import "Reachability.h"
#import "NSString+Hashing.h"
#import <AVFoundation/AVFoundation.h>
#import "CallViewController.h"
#import "AFNetworking.h"
#import "Base64Encry.h"
#import "UnKnowPhoneViewController.h"
#import <AddressBook/AddressBook.h>



@interface DSHisViewController ()<NSURLConnectionDataDelegate,UIAlertViewDelegate>

@end

@implementation DSHisViewController
{
    UILabel *_label1;
    UILabel *_label;
    UILabel *_label2;
    NSMutableData *_data;
    NSUserDefaults *users;
    NSString *_date;
    NSDate* _dat;
    NSString *_name;
    NSString*_phoneNumber;
    NSString*_userName;
    NSString*_passWoad;
    NSString *_strUrl;
    AVAudioPlayer *_player;
    NSString *_resquestString;
    NSString * _string;
    NSArray *backCallNumber;//获取回拨电话数组
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
      
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view .userInteractionEnabled =YES;
    self.navigationController.navigationBarHidden=YES;
    
    
   
}
-(void)music
{
    NetAccess *net =[NetAccess sharedNetAccess];
    if(![net haveNet])
    {
       
        return;
        
        
        
    }
    else
    {
    NSString *path =[NSString stringWithFormat:@"%@/callphoneyinpin.mp3",[[NSBundle mainBundle] resourcePath]];
    NSURL *url =[NSURL fileURLWithPath:path];
    _player =[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    [_player setVolume:7];
    [_player prepareToPlay];
    [_player play];
    }}
-(void)readAllPeoples
{
    UIImage *imaged =[UIImage imageNamed:@"cft.png"];
    UIImageView *imh =[[UIImageView alloc]initWithFrame:self.view.bounds];
    imh.image =imaged;
    [self.view addSubview:imh];
    
    
    UIButton *banckBtn =[UIButton buttonWithType:UIButtonTypeCustom];

    [banckBtn setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    banckBtn.frame =CGRectMake(30, 30, 30, 30);
    [banckBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:banckBtn];

    
    UIButton *urlBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    urlBtn.tag=23;
    [urlBtn setTitle:@"未接到来电?"  forState:UIControlStateNormal];
    urlBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [urlBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    urlBtn.frame =CGRectMake(DeviceWidth-120, 30, 100, 30);
    [urlBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:urlBtn];

    
    _label =[[UILabel alloc]initWithFrame:CGRectMake(10,70, 300, 40)];
    _label.backgroundColor =[UIColor clearColor];
    _label.font =[UIFont fontWithName:@"Arial Rounded MT Bold" size:15];
    _label.textAlignment =1;
    _label.text=@"正在接通中...";
    [self.view addSubview:_label];
    
    UIImageView *imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"call_living_p@2x.jpg"]];
    if(DeviceHeight==480)
    {
       imageView.frame =CGRectMake((DeviceWidth-80)/2, _label.frame.size.height+_label.frame.origin.y, 80, 80);
    }
    else
    {
    imageView.frame =CGRectMake((DeviceWidth-100)/2, _label.frame.size.height+_label.frame.origin.y+30, 100, 100);
    }
    [self.view addSubview:imageView];
    
    
    _label1 =[[UILabel alloc]initWithFrame:CGRectMake(10, imageView.frame.size.height+imageView.frame.origin.y+20, 300, 40)];

    _label1.text =[NSString stringWithFormat:@"%@",
                   [_tellName objectAtIndex:0]];
    _label1.font =[UIFont fontWithName:@"Arial Rounded MT Bold" size:25];
    _label1.backgroundColor =[UIColor clearColor];
    _label1.textAlignment =NSTextAlignmentCenter;
    [self.view addSubview:_label1];
  
    
    _label2 =[[UILabel alloc]initWithFrame:CGRectMake(10, _label1.frame.size.height+_label1.frame.origin.y+20, 300, 40)];
    _label2.text =[NSString stringWithFormat:@"%@",[_tellName objectAtIndex:1]];
    NSLog(@"dajiahao %@",_label2.text);
    _label2.font =[UIFont fontWithName:@"Arial Rounded MT Bold" size:25];
    _label2.backgroundColor =[UIColor clearColor];
    _label2.textAlignment =NSTextAlignmentCenter;
    [self.view addSubview:_label2];
    
    UIButton *btns =[UIButton buttonWithType:UIButtonTypeCustom];
    [btns setImage:[UIImage imageNamed:@"fvg.png"] forState:UIControlStateNormal];
    btns.frame =CGRectMake((DeviceWidth-80)/2, _label2.frame.size.height+_label2.frame.origin.y, 80, 80);
    [btns addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btns];

    UILabel*showLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, _label2.frame.size.height+_label2.frame.origin.y+40, DeviceWidth, 160)];
//    showLabel.font=[UIFont systemFontOfSize:22];
   
    showLabel.numberOfLines=3;
    showLabel.textAlignment=1;
 
    showLabel.text=[NSString stringWithFormat:@"系统正在回拨到您的手机\n%@\n请注意接听",_userName];
    [self.view addSubview:showLabel];
   
    

}
-(void)btnClick:(UIButton *)bbi
{
    if(bbi.tag==22)
    {
        [self.navigationController.tabBarController setSelectedIndex:1];
        NSLog(@"nihao");
    }
    else if(bbi.tag==23)
    {
        UnKnowPhoneViewController*unknowPhone=[[UnKnowPhoneViewController alloc]init];
        [self presentViewController:unknowPhone animated:YES completion:nil];
    }
}
// 逻辑  本地获取  假如没有有数据 网络请求 存本地 时间  号码
//有数据  对比时间  超过半个月 网络请求 原有号码有就删除  没有从新添加
//不超过时间  查找号码 没有就加添加存下的本地号码
-(void)getShuJu1
{
    NSDate *sender=[NSDate date];
    long timeSp =  (long)[sender timeIntervalSince1970];
    NSLog(@"time %ld",timeSp);
    
    NSInteger inter= [[NSUserDefaults standardUserDefaults]integerForKey:@"TimeSp"];
    NSLog(@"%@",@(inter));
    if (inter) {
        if (timeSp>inter+15*24*60*60) {
            [self getShuJu];
            [[NSUserDefaults standardUserDefaults]setInteger:timeSp forKey:@"TimeSp"];
            [[NSUserDefaults standardUserDefaults]synchronize];
        }
        else
        {
            //    读取手机通讯录
//            ABAddressBookRef addressBook = ABAddressBookCreate();
//            CFErrorRef error = NULL;
//            //    读取联系人
//            CFStringRef cfName =  CFSTR("乐语");
//            NSArray *people= (__bridge NSArray *)ABAddressBookCopyPeopleWithName(addressBook, cfName);
            
            //    people就是名字为小明的联系人数组。默认对象是CFArray，取长度方法为：CFArrayGetCount（people）
            //    为了方便强制转换成了NSArray
            //    其中一个小明
         
                backCallNumber=[[NSUserDefaults standardUserDefaults]objectForKey:@"BackCallNumber"];
                [self searchPeople];
       
        }
    }
    else
    {
        [self getShuJu];
        [[NSUserDefaults standardUserDefaults]setInteger:timeSp forKey:@"TimeSp"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    
    
}
-(void)getShuJu
{
    
    NSString*urlStr=@"http://oemapi2.leehuu.cn/YXBp/dm9zb2Vt/GetBackCallNumbers";
    NSString * parameterStr=[NSString stringWithFormat:@"userName=%@&password=%@",_userName,_passWoad];
    NSLog(@"登录111%@",[NSString stringWithFormat:@"%@  %@",urlStr,parameterStr]);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        id dict=[Base64Encry switchUrlString:urlStr switchParameterString:parameterStr];
        NSLog(@",,%@",dict);
        if([dict count])
        {
            //            dispatch_async(dispatch_get_main_queue(), ^{
            //
            //            });
            backCallNumber=[dict objectForKey:@"numbers"];
            
            //            backCallNumber=@[@"11",@"12",@"3",@"4",@"5",@"6"];
            
            NSLog(@"%@",backCallNumber);
            if (![backCallNumber isEqual:[NSNull null]]&&backCallNumber.count)
            {
                [[NSUserDefaults standardUserDefaults]setObject:backCallNumber forKey:@"BackCallNumber"];
                [[NSUserDefaults standardUserDefaults]synchronize];
                [self searchPeople];
            }
            else
            {
                return ;
                
            }
            
        }
    });
    
    
}
-(void)searchPeople
{
    //    读取手机通讯录
    ABAddressBookRef addressBook = ABAddressBookCreate();
    CFErrorRef error = NULL;
    //    读取联系人
    CFStringRef cfName =  CFSTR("乐语");
    NSArray *people= (__bridge NSArray *)ABAddressBookCopyPeopleWithName(addressBook, cfName);
    
    //    people就是名字为小明的联系人数组。默认对象是CFArray，取长度方法为：CFArrayGetCount（people）
    //    为了方便强制转换成了NSArray
    //    其中一个小明
    if ((people != nil) && [people count]>0)
    {
        //进行删除操作
        for (id person in people) {
            ABAddressBookRemoveRecord(addressBook
                                      , (__bridge ABRecordRef)(person), &error);
        }
        //保存
        ABAddressBookSave(addressBook, &error);
        CFRelease(addressBook);
        
    }
    
    [self AddPeople];
}
-(void)AddPeople
{
    
    //取得本地通信录名柄
    ABAddressBookRef tmpAddressBook = ABAddressBookCreate();
    //创建一条联系人记录
    ABRecordRef tmpRecord = ABPersonCreate();
    CFErrorRef error;
    BOOL tmpSuccess = NO;
    //Nickname 昵称
    //    CFStringRef tmpNickname = CFSTR("zhang3");
    //    tmpSuccess = ABRecordSetValue(tmpRecord, kABPersonNicknameProperty, tmpNickname, &error);
    //    CFRelease(tmpNickname);
    //First name 姓氏
    //    CFStringRef tmpFirstName = CFSTR("zhang2");
    //    tmpSuccess = ABRecordSetValue(tmpRecord, kABPersonFirstNameProperty, tmpFirstName, &error);
    //    CFRelease(tmpFirstName);
    //Last name
    CFStringRef tmpLastName = CFSTR("乐语");
    tmpSuccess = ABRecordSetValue(tmpRecord, kABPersonLastNameProperty, tmpLastName, &error);
    CFRelease(tmpLastName);
    // 电话号码数组
    NSArray *phones11 =backCallNumber;
    
    // 电话号码对应的名称
    //    NSArray *labels11 = [NSArray arrayWithObjects:@"iphone",@"home",nil];
    NSArray *labels11 = @[@"移动",
                          @"iphone",
                          @"住宅",
                          @"工作",
                          @"主要",
                          @"其他",
                          ];
    //phone number
    
    ABMutableMultiValueRef tmpMutableMultiPhones = ABMultiValueCreateMutable(kABPersonPhoneProperty);
    for (int i = 0; i < [phones11 count]; i ++) {
        ABMultiValueIdentifier mi = ABMultiValueAddValueAndLabel(tmpMutableMultiPhones,(__bridge CFStringRef)[phones11 objectAtIndex:i], (__bridge CFStringRef)[labels11 objectAtIndex:i%labels11.count], &mi);
    }
    // 写全部号码进联系人
    tmpSuccess = ABRecordSetValue(tmpRecord, kABPersonPhoneProperty, tmpMutableMultiPhones, &error);
    
    
    //保存记录－写入通讯录
    tmpSuccess = ABAddressBookAddRecord(tmpAddressBook, tmpRecord, &error);
    CFRelease(tmpRecord);
    //保存数据库
    tmpSuccess = ABAddressBookSave(tmpAddressBook, &error);
    CFRelease(tmpAddressBook);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
  
    users =[NSUserDefaults standardUserDefaults];
    NSArray *array =[users objectForKey:@"newusers1"];
    NSDictionary *dict =[array objectAtIndex:0];
     //_phoneNumber =[users objectForKey:@"postName"];
    
    _userName=[dict objectForKey:@"username"];
    
    NSLog(@"q%@",_phoneNumber);
    _passWoad=[dict objectForKey:@"userword"];
      [self readAllPeoples ];
    NSLog(@"%@",_name);
    //对通讯录的访问权限
    ABAuthorizationStatus authStatus =
    ABAddressBookGetAuthorizationStatus();
    if (authStatus == kABAuthorizationStatusAuthorized) {
        NSLog(@"11");
        NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(getShuJu1) object:nil];
        [thread start];
    }
    NSString *str = [[_tellName objectAtIndex:0] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    _strUrl=[str stringByReplacingOccurrencesOfString:@" " withString:@""];
    NetAccess*net = [NetAccess sharedNetAccess];
    if(![net haveNet])
    {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }else{
       //

      //通讯录接受电话
       NSString*name1=[self.tellName objectAtIndex:0];
        [[NSUserDefaults standardUserDefaults] setObject:name1 forKey:@"postName"];
           //直接拨打接受电话
           NSString*name= [[NSUserDefaults standardUserDefaults] objectForKey:@"postName"];
        NSLog(@"ppp%@ %@",_userName,name);

        NSString*urlStr=@"http://oemapi2.leehuu.cn/YXBp/dm9zb2Vt/TWFrZUNhbGxCYWNr";
        NSString * parameterStr=[NSString stringWithFormat:@"Y2FsbGVy=%@&password=%@&Y2FsbGVk=%@&isShow=1&parent=2645421",[Base64Encry switchBase64String:_userName],_passWoad,[Base64Encry switchBase64String:name]];
        NSLog(@"登录%@",[NSString stringWithFormat:@"%@  %@",urlStr,parameterStr]);
        id dict=[Base64Encry switchUrlString:urlStr switchParameterString:parameterStr];
            NSLog(@"获取到的数据为：%@",dict);
            self.excString=[dict objectForKey:@"exception"];
            self.retString=[dict objectForKey:@"retCode"];
//        [self performSelector:@selector(sleepAction) withObject:nil afterDelay:10.0f];
            if (![self.retString intValue])
            {
                
                _label.text =@"呼叫成功，请等待...";
//               
//                //获取通话状态
                self.callCenter = [[CTCallCenter alloc] init];
                self.callCenter.callEventHandler=^(CTCall*call){

                    if (call.callState ==  CTCallStateIncoming){
                        NSLog(@"call station111");
//                        [[NSNotificationCenter defaultCenter]postNotificationName:@"textFieldgg" object:@"s"];
                        [self btnClick];
                    }
                    
                };
                BOOL switchIsOn=YES;
                switchIsOn=[[NSUserDefaults standardUserDefaults]boolForKey:@"SWITCH"];
              
                if (switchIsOn) {
                    [self performSelectorInBackground:@selector(music) withObject:self];
                    
                }
                else
                {
                }
                return;
                
            }
            else
            {
                _label.text=@"呼叫失败";
                NSString*message=[NSString stringWithFormat:@"您的%@\n呼叫不成功",self.excString];
                UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil ];
                alert.tag=44;
                alert.delegate=self;
                
                [alert show];
                
                return;
}
            }
    

}
-(void)sleepAction
{
    [self dismissModalViewControllerAnimated:YES];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==44) {
        if (buttonIndex==0) {
            [self dismissModalViewControllerAnimated:YES];
        }
    }
}

-(void)get
{
    //    if ([[UIDevice currentDevice] proximityState] == NO)
    //    {
    //        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    //    }
    sleep(12);
    [_player pause];
    [NSThread detachNewThreadSelector:@selector(inty) toTarget:self withObject:nil];
}
-(void)inty
{
    sleep(3);
    [self btnClick];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_player pause];
   // [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    [self.view removeFromSuperview];
  
}
-(void)btnClick
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end